package com.scf.loan.controller;

import com.aliyun.oss.OSSClient;
import com.scf.loan.Service.FileService;
import com.scf.loan.entity.Appendix;
import com.scf.uitl.ResponseResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/files")

public class FileController {
	@Resource
	private OSSClient ossClient;
	@Resource
			private FileService fileService;
	//
	ResponseResult responseResult =new ResponseResult();
	private static final String BUCKETNAME = "woniuxyoss";
	private String baseUrl = "https://woniuxyoss.oss-cn-chengdu.aliyuncs.com/";

	// 上传文件，并写入数据库
	@PostMapping("/upload")
	public ResponseResult upload(@RequestParam("file") MultipartFile file,@RequestParam("plid") Integer plid){
		System.out.println(file);
		System.out.println(plid);
		//1.获得文件名字
		String fileName = file.getOriginalFilename();
		//得到后置名
		String suffix=fileName.substring(fileName.indexOf("."));
		//新名字
		fileName = UUID.randomUUID().toString()+suffix;
		//2.获取文件流
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();
			//

			ossClient.putObject(BUCKETNAME,fileName,inputStream);

			//设置文件有效期  60天
			Date date = new Date(new Date().getTime()+ 1000*3600*24*60);
			//获取url
			URL url = ossClient.generatePresignedUrl(BUCKETNAME,fileName,date);

			Appendix appendix = new Appendix(0,fileName,baseUrl+fileName,plid);
			int upload = fileService.upload(appendix);
			//返回数据
			Appendix fileResult = new Appendix();
			fileResult.setAname(fileName);
			fileResult.setAurl(baseUrl+fileName);
			//
			responseResult.setMessage("success");
			responseResult.setData(fileResult);
			//
			return responseResult;
		}catch (IOException e){
			ResponseResult responseResult = new ResponseResult();
			responseResult.setMessage("上传失败");
			responseResult.setCode(500);

			e.printStackTrace();

		}
		return responseResult;
	}

	//删除文件
	@PostMapping("/del")
	public ResponseResult<String> del(String fileName){
		ossClient.deleteObject(BUCKETNAME,fileName);
		responseResult.setCode(200);
		responseResult.setMessage("删除成功！");
		return responseResult;
	}

//查看所有图片
	@PostMapping("/allFile")
	public ResponseResult allFile(@RequestBody Appendix appendix){
		System.out.println(appendix.getPlid());
		List<Appendix> appendices = fileService.allFile(appendix.getPlid());
		System.out.println(appendices);
		if(appendices.size()!=0) {
			responseResult.setData(appendices);
			responseResult.setCode(200);
			return responseResult;
		}else {
			responseResult.setCode(500);
			return responseResult;
		}

	}
}
